﻿using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Xml.Serialization;
using Vlc.DotNet.Core;
using Vlc.DotNet.Wpf;

namespace StreamersBestFriend
{
	public partial class MainWindow : Window
	{
		#region vars

		VlcMediaPlayer _vlcmediaplayer;
        private bool myPositionChanging;

		#endregion

		public MainWindow()
		{
            //initializes with specified irc settings and writes them in an xml; reloads if xml exists
			InitializeComponent();
			BotSettings _settings = new BotSettings();
            if (File.Exists(@"D:\Dokumente\IrcBotSettings.xml"))
			{
				XmlSerializer deserializer = new XmlSerializer(typeof(BotSettings));
                TextReader textReader = new StreamReader(@"D:\Dokumente\IrcBotSettings.xml");
				_settings = (BotSettings)deserializer.Deserialize(textReader);
				textReader.Close();
			}
			else
			{
				_settings.IRC_Username = ""; // irc/twitch loginname
                _settings.IRC_Password = ""; // oauth token
				_settings.IRC_TargetChannel = ""; // irc channel
				_settings.IRC_Serveradress = "irc.twitch.tv";
				_settings.VLC_WaveOutDevice = "Line 1 (Virtual Audio Cable) ($1,$64)";
				_settings.VLC_LibVlcDllsPath = @"C:\Program Files (x86)\VideoLAN\VLC\";
				_settings.VLC_LibVlcPluginsPath = @"C:\Program Files (x86)\VideoLAN\VLC\plugins\<";
				_settings.IRC_Serverport = 6667;
				_settings.DebugMode = true;
			}
			_vlcmediaplayer = new VlcMediaPlayer(_settings, this);

            //initialize vlc controls for ui
            _vlcmediaplayer._vlcplayer.PositionChanged += VlcControlOnPositionChanged;
            _vlcmediaplayer._vlcplayer.TimeChanged += VlcControlOnTimeChanged;
		}

		#region buttons

		private void ButtonPreviousClick(object sender, RoutedEventArgs e)
		{
			_vlcmediaplayer._vlcplayer.Previous();
		}

		public void ButtonNextClick(object sender, RoutedEventArgs e)
		{
			Debug.WriteLineIf(_vlcmediaplayer.TracksInPlaylist > 0, "_vlcplayer.Medias.Count = " + _vlcmediaplayer.TracksInPlaylist);
			if (_vlcmediaplayer._vlcplayer.Media != null && _vlcmediaplayer.TracksInPlaylist > 0)
				_vlcmediaplayer._vlcplayer.Next();
		}

		private void CheckboxMuteCheckedChanged(object sender, RoutedEventArgs e)
		{
			_vlcmediaplayer._vlcplayer.AudioProperties.IsMute = _CheckboxMute.IsChecked == true;
		}

		private void SliderVolumeValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
		{
			_vlcmediaplayer._vlcplayer.AudioProperties.Volume = Convert.ToInt32(sliderVolume.Value);
		}

		private void ButtonStopClick(object sender, RoutedEventArgs e)
		{
            if(_vlcmediaplayer._vlcplayer.Media != null)
			_vlcmediaplayer._vlcplayer.Stop();
		}

		private void ButtonPauseClick(object sender, RoutedEventArgs e)
		{
            if (_vlcmediaplayer._vlcplayer.Media != null)
			_vlcmediaplayer._vlcplayer.Pause();
		}

		private void ButtonPlayClick(object sender, RoutedEventArgs e)
		{
            if (_vlcmediaplayer._vlcplayer.Media == null)
			_vlcmediaplayer._vlcplayer.Play();
		}

        #region slidercontrol

        private void SliderMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            myPositionChanging = true;
            _vlcmediaplayer._vlcplayer.PositionChanged -= VlcControlOnPositionChanged;
        }

        private void SliderMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _vlcmediaplayer._vlcplayer.Position = (float)sliderPosition.Value;
            _vlcmediaplayer._vlcplayer.PositionChanged += VlcControlOnPositionChanged;

            myPositionChanging = false;
        }

        private void SliderValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (myPositionChanging)
            {
                _vlcmediaplayer._vlcplayer.Position = (float)e.NewValue;
            }
            //Update the current position text when it is in pause
            var duration = _vlcmediaplayer._vlcplayer.Media == null ? TimeSpan.Zero : _vlcmediaplayer._vlcplayer.Media.Duration;
            var time = TimeSpan.FromMilliseconds(duration.TotalMilliseconds * _vlcmediaplayer._vlcplayer.Position);
            _TextBlockDuration.Text = string.Format(
                "{0:00}:{1:00}:{2:00} / {3:00}:{4:00}:{5:00}",
                time.Hours,
                time.Minutes,
                time.Seconds,
                duration.Hours,
                duration.Minutes,
                duration.Seconds);
        }

        private void VlcControlOnPositionChanged(VlcControl sender, VlcEventArgs<float> e)
        {
            if (myPositionChanging)
            {
                // User is currently changing the position using the slider, so do not update. 
                return;
            }

            sliderPosition.Value = e.Data;
        }

        private void VlcControlOnTimeChanged(VlcControl sender, VlcEventArgs<TimeSpan> e)
        {
            if (_vlcmediaplayer._vlcplayer.Media == null)
                return;
            var duration = _vlcmediaplayer._vlcplayer.Media.Duration;
            _TextBlockDuration.Text = string.Format(
                "{0:00}:{1:00}:{2:00} / {3:00}:{4:00}:{5:00}",
                e.Data.Hours,
                e.Data.Minutes,
                e.Data.Seconds,
                duration.Hours,
                duration.Minutes,
                duration.Seconds);
        }

        #endregion

        #endregion

        private void Button_Click(object sender, RoutedEventArgs e)
		{
			_vlcmediaplayer.requestSong("http://www.youtube.com/watch?v=v7BddpYYNGk");
			_vlcmediaplayer.requestSong("http://www.youtube.com/watch?v=a2ViM6HE7O0");
			_vlcmediaplayer.requestSong("http://www.youtube.com/watch?v=6g477J651Mo");
			_vlcmediaplayer.requestSong("http://www.youtube.com/watch?v=3bO2h7zvEWk");

		}

		private void Button_ReconnectIrc(object sender, RoutedEventArgs e)
		{
            _vlcmediaplayer._ircclient.IrcClient_Disconnected(null, null);
		}

		#region functions

		public void writeConsole(String s)
		{
			this.Dispatcher.Invoke(() =>
			{
				_Console.Text = "[" + DateTime.Now.ToString("HH:mm:ss") + "] " + s + " \n" + _Console.Text;
			});
		}

		public void setMainWindowTitle(String title)
		{
			this.Dispatcher.Invoke(() =>
			{
				this.Title = "Musicbot: Now playing " + title;
			});
		}
		#endregion
	}
}
